<!-- components/charts/HotKeysChart.vue -->
<template>
  <div class="hot-keys-chart">
    <v-chart v-if="!loading && data.length > 0"
      :option="chartOption"
      :loading="loading"
      autoresize
      class="chart" />
    <div v-else-if="loading"
      class="loading-container">
      <el-icon class="is-loading">
        <Loading />
      </el-icon>
      <span>加载中...</span>
    </div>
    <div v-else
      class="empty-container">
      <el-empty description="暂无热点数据" />
    </div>
  </div>
</template>

<script setup>
import { computed } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { BarChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  GridComponent
} from 'echarts/components'
import VChart from 'vue-echarts'

use([
  CanvasRenderer,
  BarChart,
  TitleComponent,
  TooltipComponent,
  GridComponent
])

const props = defineProps({
  data: {
    type: Array,
    default: () => []
  },
  loading: {
    type: Boolean,
    default: false
  }
})

const chartOption = computed(() => ({
  title: {
    text: '热点数据访问统计',
    left: 'center',
    textStyle: {
      fontSize: 16,
      fontWeight: 'normal'
    }
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    },
    formatter: (params) => {
      const data = params[0]
      return `Key: ${data.name}<br/>访问次数: ${data.value}<br/>ID: ${props.data[data.dataIndex]?.id || 'N/A'}`
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '15%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: props.data.map(item => item.key.length > 15 ? item.key.substring(0, 15) + '...' : item.key),
    axisLabel: {
      rotate: 45,
      fontSize: 10
    }
  },
  yAxis: {
    type: 'value',
    name: '访问次数',
    axisLabel: {
      formatter: '{value}'
    }
  },
  series: [
    {
      type: 'bar',
      data: props.data.map(item => ({
        value: item.accessCount,
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: '#409EFF' },
              { offset: 1, color: '#67C23A' }
            ]
          }
        }
      })),
      barWidth: '60%',
      label: {
        show: true,
        position: 'top',
        fontSize: 10
      }
    }
  ]
}))
</script>

<style scoped>
.hot-keys-chart {
  width: 100%;
  height: 100%;
}

.chart {
  width: 100%;
  height: 100%;
}

.loading-container,
.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
}

.loading-container .el-icon {
  font-size: 32px;
  margin-bottom: 10px;
}
</style>